import modelExtend from 'dva-model-extend'
import { lwjPageModel } from 'utils/model'
import { routerRedux } from 'dva/router'
import { Modal, message } from 'antd'
import {turnToTreeData} from 'utils/index'
import { query, queryStoreList, queryTypeList, link, alllink, queryUserByKeywords, library, allList, assignStore } from 'services/product/product'

export default modelExtend(lwjPageModel, {
  //命名空间
  namespace: 'storelist',
  //数据
  state: {
    list: [],
    //分页
    pagination: {
      //与lwjTable交互要用current
      current: 1,
      total: 0,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      showQuickJumper: true,
      defaultPageSize: 10,
      pageSize: 10
    },
    //筛选参数
    searchKeyword: '',
    store: {
      modalVisible: false,
      selectedRows: [],
      selectedRowKeys: [],
      list: [],
      pagination: {
        //与lwjTable交互要用current
        current: 1,
        total: 0,
        showTotal: total => `共 ${total} 条`,
        showSizeChanger: true,
        showQuickJumper: true,
        defaultPageSize: 10,
        pageSize: 10
      },
      id: null,
      libraryVisible: false,
      fastVisible: false,
      currentItem: {},
      queryParam: {},
      commodityStoreList: [],
      currentOption: ""
    },
    cateList: [],
    originCateList: []
  },
  subscriptions: {
    //页面初始化事件
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        if (pathname === '/product/store') {
          dispatch({
            type: 'reset'
          })
          dispatch({
            type: 'allList'
          })
          dispatch({
            type: 'query',
            payload: {
              start: 0,
              limit: 10
            }
          })
          dispatch({
            type: 'queryCateList'
          })
        }
      })
    }
  },
  effects: {
    * allList({
      payload
    }, { select, call, put }) {
      const data = yield call(allList, payload);
      yield put({
        type: 'setCommodityStoreList',
        payload: data.result
      })
    },
    * queryCateList({}, { select, call, put }) {
      const {result: data} = yield call(queryTypeList);
      let _temp = turnToTreeData(data, 'name', 'id', 'pid');
      yield put({
        type: 'setCateList',
        cateList: _temp,
        originCateList: data
      })
    },
    * assignStore({
      payload
    }, { select, call, put }) {
      yield call(assignStore, payload);
      Modal.success({
        title:'操作成功',
        content:'快速分配商品库成功'
      })
    },
    * library({
      payload
    }, { select, call, put }) {
      const data = yield call(library, payload);
      yield put(routerRedux.push('/success', { listUrl: '/product/store', detailUrl: '/product/store' }));
    },
    //请求异步数据
    * productList({ payload }, { select, call, put }) {
      const store = yield select(({ storelist }) => storelist.store);
      //调用异步service
      const { result: data } = yield call(query, {
        // 与service交互要用current,但是lwjTable返回的是start
        start: payload.start,
        limit: payload.limit,
        distributorId: store.id,
        sort: 'id',
        order: 'DESC',
        ...store.queryParam
      });
      //调用同步事件
      yield put({
        type: 'productSuccess',
        payload: {
          list: data.content,
          pagination: {
            current: payload.start + 1,
            total: data.totalElements,
            showTotal: total => `共 ${total} 条`,
            showSizeChanger: true,
            showQuickJumper: true,
            defaultPageSize: 10,
            pageSize: data.size
          }
        }
      });
    },
    * query({ payload }, { select, call, put }) {
      const searchKeyword = yield select(({ storelist }) => storelist.searchKeyword);
      //调用异步service
      const data = yield call(queryStoreList, {
        // 与service交互要用current,但是lwjTable返回的是start
        queryParam: {
          limit: payload.limit,
          start: payload.start,
          order: "DESC",
          sort: "createTime",
          name: searchKeyword
        }
      });
      //调用同步事件
      yield put({
        type: 'success',
        payload: {
          list: data.content,
          pagination: {
            current: payload.start + 1,
            total: data.totalElements,
            showTotal: total => `共 ${total} 条`,
            showSizeChanger: true,
            showQuickJumper: true,
            defaultPageSize: 10,
            pageSize: data.size
          }
        },
      });
    },
    //关联&取关
    *link({ param, flag }, { select, call, put }) {
      yield call(link, param)
      const store = yield select(({ storelist }) => storelist.store);
      message.success("操作成功");
      const pagination = yield select(({ storelist }) => storelist.store.pagination);
      yield put({
        type: 'productList',
        payload: {
          start: pagination.current - 1,
          limit: pagination.pageSize,
        }
      })
      if (flag) {
        yield put({
          type: 'setSelectedRows',
          selectedRows: [],
          selectedRowKeys: []
        })
      }
    },
    //全部关联&取关
    *alllink({params}, { select, call, put }) {
      yield call(alllink, params);
      const pagination = yield select(({ storelist }) => storelist.store.pagination); 
      yield put({
        type: 'productList',
        payload: {
          start: pagination.current - 1,
          limit: pagination.pageSize,
        }
      })
      yield put({
        type: 'setSelectedRows',
        selectedRows: [],
        selectedRowKeys: []
      })
    }
  },
  reducers: {
    //同步state数据
    success(state, { payload }) {
      return {
        ...state,
        list: payload.list,
        pagination: payload.pagination
      }
    },
    //同步state数据
    changeFilter(state, { searchKeyword }) {
      return {
        ...state,
        searchKeyword
      }
    },
    changeRow(state, { item }) {
      let store = state.store;
      let list = state.store.list;
      let index = list.indexOf(item);
      list[index].enabled = !list[index].enabled;
      store.list = list;
      return {
        ...state,
        store
      }
    },
    toggleModal(state, { flag, id }) {
      return {
        ...state,
        store: {
          modalVisible: flag,
          selectedRowKeys: [],
          selectedRows: [],
          list: [],
          id: id,
          pagination: {
            //与lwjTable交互要用current
            current: 1,
            total: 0,
            showTotal: total => `共 ${total} 条`,
            showSizeChanger: true,
            showQuickJumper: true,
            defaultPageSize: 10,
            pageSize: 10
          },
          queryParam: {}
        }
      }
    },
    changeParam(state, { queryParam }) {
      let store = state.store;
      store.queryParam = queryParam;
      return {
        ...state,
        store
      }
    },
    onSelectChange(state, { selectedRowKeys, selectedRows }) {
      let store = state.store;
      store.selectedRowKeys = selectedRowKeys;
      store.selectedRows = selectedRows;
      return {
        ...state,
        store
      }
    },
    productSuccess(state, { payload }) {
      let store = state.store;
      store.pagination = payload.pagination;
      store.list = payload.list;
      return {
        ...state,
        store
      }
    },
    setSelectedRows(state, { selectedRows, selectedRowKeys }) {
      let store = state.store;
      store.selectedRows = selectedRows;
      store.selectedRowKeys = selectedRowKeys;
      return {
        ...state,
        store
      }
    },
    setLibraryVisible(state, { payload }) {
      return {
        ...state,
        libraryVisible: payload
      }
    },
    setFastVisible(state, { payload }) {
      return {
        ...state,
        fastVisible: payload
      }
    },
    setCurrentItem(state, { payload }) {
      return {
        ...state,
        currentItem: payload
      }
    },
    setCateList(state, { cateList, originCateList }) {
      return {
        ...state,
        cateList: cateList,
        originCateList: originCateList
      }
    },
    setCurrentOption(state, { payload }) {
      return {
        ...state,
        currentOption: payload
      }
    },
    setCommodityStoreList(state, { payload }) {
      return {
        ...state,
        commodityStoreList: payload
      }
    },

    reset() {
      return {
        list: [],
        //分页
        pagination: {
          //与lwjTable交互要用current
          current: 1,
          total: 0,
          showTotal: total => `共 ${total} 条`,
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          pageSize: 10
        },
        //筛选参数
        searchKeyword: '',
        store: {
          modalVisible: false,
          selectedRows: [],
          selectedRowKeys: [],
          list: [],
          pagination: {
            //与lwjTable交互要用current
            current: 1,
            total: 0,
            showTotal: total => `共 ${total} 条`,
            showSizeChanger: true,
            showQuickJumper: true,
            defaultPageSize: 10,
            pageSize: 10
          },
          id: null,
          queryParam: {}
        }
      }
    }
  }
})
